package com.yuandian.management.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.management.entity.ConfBlacklistResource;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.management.mapper.ConfBlackListMapper;
import com.yuandian.management.service.ConfBlackListService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * IT云化资源配置-黑名单
 */
@Service
@RequiredArgsConstructor
public class ConfBlackListServiceImpl implements ConfBlackListService {

	@Autowired
	private ConfBlackListMapper confBlackListMapper;

	/**
	 * 分页查询
	 *
	 * @param confBlacklistResource 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfBlacklistResource> listPage(ConfBlacklistResource confBlacklistResource) {
		return confBlackListMapper.listPage(new Page<>(confBlacklistResource.getPageNum(), confBlacklistResource.getPageSize()), confBlacklistResource);
	}

	/**
	 * 删除服务资源黑名单
	 *
	 * @param brv 参数
	 * @return Result
	 */
	@Override
	public R<String> deleteBlackList(ConfBlacklistResource brv) {
		int status = 0;
		// 1、用确认url查询要删除的黑名单列表
		ConfBlacklistResource dbBrv = new ConfBlacklistResource();
		dbBrv.setConfirmedUrl(brv.getConfirmedUrl());
		List<ConfBlacklistResource> blacklistResources = confBlackListMapper.listByCondition(dbBrv);
		if (blacklistResources.isEmpty()) {
			// 无删除的黑名单
			return R.failed(null, "无删除的黑名单");
		}

		// 2、更新业务服务资源为未使用，供数据重组重新发现
		List<String> urls = new ArrayList<>();
		List<Long> ids = new ArrayList<>();
		for (ConfBlacklistResource blacklistResource : blacklistResources) {
			urls.add(blacklistResource.getOriginalUrl());
			ids.add(blacklistResource.getId());
		}
		if (!urls.isEmpty()) {
			confBlackListMapper.updateBusinessResourceNoUsed(urls);
		}
		confBlackListMapper.updateBusinessResourceNoUsed2();

		// 3、批量删除黑名单
		if (!ids.isEmpty()) {
			status = confBlackListMapper.deleteByIdBatch(ids);
			if (status <= 0) {
				// 删除黑名单失败
				return R.failed(null, "删除黑名单失败");
			}
		}
		return R.ok();
	}

	/**
	 * 批量新增服务资源黑名单
	 *
	 * @param blacklistResourceList@return int
	 */
	@Override
	public int insertBlackListResourceBatch(List<ConfBlacklistResource> blacklistResourceList) {
		return confBlackListMapper.insertBlackListResourceBatch(blacklistResourceList);
	}

	/**
	 * 新增服务资源黑名单
	 *
	 * @param blacklistResource 参数
	 * @return int
	 */
	@Override
	public int insertBlackListResource(ConfBlacklistResource blacklistResource) {
		return confBlackListMapper.insertBlackListResource(blacklistResource);
	}
}
